/*
 * @Copyright: 2016 www.yyfax.com Inc. All rights reserved.
 */
package com.jaws.core.compatible.spring;

import java.util.Map;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import com.jaws.core.common.util.JacksonUtil;

/**
 * 封装一下NamedParameterJdbcTemplate,捕捉一些特殊异常
 * 
 * @author jiangmy
 * @date 2016-08-12 09:12:25
 * @since v1.0.0
 */
public class YYNamedParameterJdbcTemplate extends NamedParameterJdbcTemplate {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 构造函数
	 * 
	 * @param dataSource
	 */
	public YYNamedParameterJdbcTemplate(DataSource dataSource) {
		super(dataSource);
	}

	/**
	 * 封装一下几个特殊方法,捕捉特殊异常
	 */
	@Override
	public <T> T queryForObject(String sql, Map<String, ?> paramMap, RowMapper<T> rowMapper) {
		try {
			return super.queryForObject(sql, paramMap, rowMapper);
		} catch (EmptyResultDataAccessException e) {
			logger.debug("查询对象出现空集合,sql:{}", sql);
			logger.debug("参数:{}", JacksonUtil.toJson(paramMap));
			return null;
		}
	}

	/**
	 * 封装一下几个特殊方法,捕捉特殊异常
	 */
	@Override
	public <T> T queryForObject(String sql, SqlParameterSource paramSource, RowMapper<T> rowMapper) {
		try {
			return super.queryForObject(sql, paramSource, rowMapper);
		} catch (EmptyResultDataAccessException e) {
			logger.debug("查询对象出现空集合,sql:{}", sql);
			logger.debug("参数:{}", JacksonUtil.toJson(paramSource));
			return null;
		} catch (IncorrectResultSizeDataAccessException e) {
			logger.info("查询单条对象时出现多条集合,sql:{}", sql);
			logger.info("参数:{}", JacksonUtil.toJson(paramSource));
			return null;
		}
	}

	/**
	 * 插入并返回主键,注意一定要有自增主键的表才能使用
	 */
	public int insertForPK(String sql, SqlParameterSource paramSource) {
		KeyHolder keyHolder = new GeneratedKeyHolder();
		int i = super.update(sql, paramSource, keyHolder);
		if (i == 1) {
			return keyHolder.getKey().intValue();
		}
		// throw new SQLException("insert failed");
		logger.info("insert ignored sql:{}", sql);
		return 0;
	}

}
